package top.fengleifeng.question;

import java.util.LinkedList;
import java.util.Queue;

/**
 * @program: leetcode-test
 * @description:
 * @author: fengleifeng
 * @create: 2020-09-28 15:38
 **/
public class Num117填充每个节点的下一个右侧节点指针II {
    /*
// Definition for a Node.
class Node {
    public int val;
    public Node left;
    public Node right;
    public Node next;

    public Node() {}

    public Node(int _val) {
        val = _val;
    }

    public Node(int _val, Node _left, Node _right, Node _next) {
        val = _val;
        left = _left;
        right = _right;
        next = _next;
    }
};
*/
    //层序遍历
    class Solution {
        public Node connect(Node root) {
            if(null==root){
                return null;
            }
            Queue<Node> queue = new LinkedList<>();
            queue.add(root);
            while (!queue.isEmpty()){
                int size = queue.size();
                Queue<Node> nextQueue = new LinkedList<>();
                for (int i = 0; i < size; i++) {
                    Node poll = queue.poll();
                    poll.next = queue.peek();
                    if(null!=poll.left){
                        nextQueue.add(poll.left);
                    }
                    if(null!=poll.right){
                        nextQueue.add(poll.right);
                    }
                }
                queue.addAll(nextQueue);
            }
            return root;
        }
    }
    class Node {
        public int val;
        public Node left;
        public Node right;
        public Node next;

        public Node() {}

        public Node(int _val) {
            val = _val;
        }

        public Node(int _val, Node _left, Node _right, Node _next) {
            val = _val;
            left = _left;
            right = _right;
            next = _next;
        }
    }
}
